package com.cloudwave.trailends.action;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cloudwave.base.action.AppAction;
import com.cloudwave.base.entity.ResultEntity;
import com.cloudwave.fwcore.entity.Result;
import com.cloudwave.trailends.beans.UserHomeBean;
import com.cloudwave.trailends.entity.UserInfoEntity;
import com.cloudwave.trailends.service.UserService;

@Controller
@RequestMapping("/api/user")
public class UserAction extends AppAction {
	private static Logger logger = LoggerFactory.getLogger(UserAction.class);
	
	@Resource
	private UserService userService;
	
	
	@RequestMapping("/home")
	public @ResponseBody ResultEntity loadUserHome(@RequestParam("id") Long id) {
		if (id == null || id == 0) {
			return resultEntity.failure(Result.ILLEGAL_REQUEST_PARAMS);
		}
		try {
			UserHomeBean uhb = this.userService.loadUserHome(id);
			return resultEntity.success(uhb);
		} catch (Exception e) {
			return resultEntity.failure(Result.FIND_FAILURE);
		}
	}
	
	@RequestMapping("/baseinfo/update")
	public @ResponseBody ResultEntity updateBaseInfo(@RequestParam(value="data") String data) {
		UserInfoEntity userInfo = null;
		try {
			userInfo = JSON.parseObject(data, UserInfoEntity.class);
		} catch (Exception e) {
			logger.error("user info parse error!", e);
			return resultEntity.failure(Result.PARSE_FAILURE);
		}
		
		if ( userInfo != null ) {
			if ( userInfo.getUserId() == null
					|| userInfo.getUserId() == 0 ) {
				userInfo.setUserId(super.userId);
			}
		} else {
			return resultEntity.failure(Result.ILLEGAL_REQUEST_PARAMS);
		}
		
		try {
			userService.update(userInfo);
			return resultEntity.success();
		} catch (Exception e) {
			logger.error("user info update error!", e);
			return resultEntity.failure(Result.UPDATE_FAILURE);
		}
	}
}
